package com.hfstu.framework.webmsg;




import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;

import com.hfstu.framework.common.ApplicationSessionSchema;



/**
 * web message 管理
 * 
 * @author dejunx
 * 
 */
public class WebMessageManager {

	private static Log log = LogFactory.getLog(WebMessageManager.class);

	@SuppressWarnings("unchecked")
	public static void addUserSystemToMap(String userId, String systemCode,
			HttpServletRequest request) {
		WebContext wctx = WebContextFactory.get();
		ScriptSession scriptSession = wctx
				.getScriptSession();
		ServletContext application = request.getSession().getServletContext();
		Map<String, Map<String, ScriptSession>> map = (Map<String, Map<String, ScriptSession>>) application
				.getAttribute(ApplicationSessionSchema.DWR_ONLINE_INFO);
		if (map == null) {
			map = new HashMap<String, Map<String, ScriptSession>>();
		}
		Map<String, ScriptSession> systemScriptSession = null;
		if (map.get(userId) == null) {
			systemScriptSession = new HashMap<String, ScriptSession>();
		} else {
			systemScriptSession = map.get(userId);
		}
		systemScriptSession.put(systemCode, scriptSession);
		map.put(userId, systemScriptSession);
		log.info("dwr userId=" + userId + map.get(userId).values());
		application.setAttribute(ApplicationSessionSchema.DWR_ONLINE_INFO, map);
	}

	@SuppressWarnings("unchecked")
	public static void removeUserSystemToMap(String userId, String systemCode,
			HttpServletRequest request) {
		ServletContext application = request.getSession().getServletContext();
		Map<String, Map<String, ScriptSession>> map = (Map<String, Map<String, ScriptSession>>) application
				.getAttribute(ApplicationSessionSchema.DWR_ONLINE_INFO);
		if (map != null) {
			Map<String, ScriptSession> systemScriptSession = map.get(userId);
			if (systemScriptSession != null) {
				systemScriptSession.remove(systemCode);
				if (systemScriptSession.size() == 0) {
					map.remove(userId);
					request.getSession().invalidate();
				}
			}
		}
		application.setAttribute(ApplicationSessionSchema.DWR_ONLINE_INFO, map);
	}
}
